<?php

namespace common\model;

use common\service\OptionsService;
use think\model\RelationModel;

class OptionsModel extends RelationModel
{

    //自动验证
    protected $_validate = [
        ['name', '', '', self::MUST_VALIDATE, 'require', self::MODEL_INSERT],//必须字段
        ['name', '1,128', '', self::EXISTS_VALIDATE, 'length'],
        ['type', '0,128', '', self::EXISTS_VALIDATE, 'length'],
        ['type', '', '', self::EXISTS_VALIDATE, 'alphaDash'],
        ['config', '', '', self::EXISTS_VALIDATE, 'array'],
        ['name', '', '', self::EXISTS_VALIDATE, 'unique'],
    ];

    //自动完成
    protected $_auto = [
        ['config', 'json_encode', self::EXISTS_VALIDATE, 'function'],
        ['uuid', 'create_uuid', self::MODEL_INSERT, 'function']
    ];


    /**
     * 获取器：配置
     * @param $value
     * @return array|mixed
     */
    public function getConfigAttr($value)
    {
        if (!empty($value)) {
            return json_decode($value, true);
        }
        return [];
    }

    /**
     * 更新指定Options设置
     * @param $params
     * @return array|bool
     * @throws \Exception
     */
    public function updateOptionsData($params)
    {
        $params['name'] = $params['options_name'];
        OptionsService::getInstance()->clearOptionCache([$params['options_name']]); // 清除 project_initiation 缓存
        $options = $this->where(['name' => $params['options_name']])->find();
        if (!empty($options)) {
            $params['id'] = $options['id'];
            $params['config'] = array_merge(json_decode($options['config'], true), $params['config']);
            return $this->modifyItem($params);
        } else {
            $addData = $params;
            return $this->addItem($addData);
        }
    }
}
